package com.ruoyi.drawing.test;

import lombok.extern.slf4j.Slf4j;

/**
 * 最长公共前缀
 *
 * @author ZhangYu
 * @date 2024/10/19 17:38
 */
@Slf4j
public class LongestCommonPrefix {

    public static void main(String[] args) {
        String[] stringArray = {"flower", "flow", "flight"};
        log.info("----------------------------------------------------------------{}", getLongestCommonPrefix(stringArray));
    }

    /**
     * 示例 1：
     * <p>
     * 输入：strs = ["flower","flow","flight"]
     * 输出："fl"
     * 示例 2：
     * <p>
     * 输入：strs = ["dog","racecar","car"]
     * 输出：""
     * 解释：输入不存在公共前缀。
     *
     * @param stringArray 输入数组
     * @return 最长公共前缀
     */
    private static String getLongestCommonPrefix(String[] stringArray) {
        StringBuilder result = new StringBuilder();
        char[] oneStringArray = stringArray[0].toCharArray();
        for (int i = 0; i < oneStringArray.length; i++) {
            char iChar = oneStringArray[i];
            for (int j = 1; j < stringArray.length; j++) {
                char[] jStringArray = stringArray[j].toCharArray();
                if (jStringArray.length - 1 < i) {
                    return result.toString();
                }
                if (jStringArray[i] != iChar) {
                    return result.toString();
                }
            }
            result.append(iChar);
        }
        return result.toString();
    }

}
